package com.wyatt.wytplatform.mvvm_login.data.repository

import com.wyatt.wytplatform.mvvm_login.data.local.UserDao
import com.wyatt.wytplatform.mvvm_login.data.model.LoginRequest
import com.wyatt.wytplatform.mvvm_login.data.model.LoginResponse
import com.wyatt.wytplatform.mvvm_login.data.model.UserEntity
import com.wyatt.wytplatform.mvvm_login.data.remote.ApiService
import com.wyatt.wytplatform.mvvm_login.utils.Resource
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import javax.inject.Inject

class UserRepository @Inject constructor(
    private val apiService: ApiService,
    private val userDao: UserDao
) {

    fun login(username: String, password: String): Flow<Resource<LoginResponse>> = flow {
        try {
            emit(Resource.Loading())
            val response = apiService.login(LoginRequest(username, password))
            emit(Resource.Success(response))
        } catch (e: Exception) {
            emit(Resource.Error(message = e.message ?: "未知错误"))
        }
    }

    suspend fun saveUser(user: UserEntity) {
        userDao.saveUser(user)
    }

    suspend fun getUser(): UserEntity? {
        return userDao.getUser()
    }

    suspend fun deleteUser() {
        userDao.deleteUser()
    }
}    